<?php

  function addTag($url, $url_param, $tag) {
    $return_string = "";

    if (!isset($_SESSION['user_name'])) {
      $return_string .= "<returncode>0</returncode>\n";
      $return_string .= "<errormessage>You're not logged in!</errormessage>\n";
      return $return_string;
    }

    $query = "SELECT id FROM WebPage WHERE url = '" . $url . "'";
    $result = mysql_query($query);
    $webpage_id = -1;
    if (mysql_num_rows($result) == 0) {
      $webpage_id = registerPage($url);
    } else {
      $result_row = mysql_fetch_assoc($result);
      $webpage_id = $result_row['id'];
    }

    $webpagequery_id = getPageParameterId($webpage_id, $url_param);
    $user_id = $_SESSION['user_id'];
    $query = "SELECT * FROM Tag WHERE text='$tag'";
    $result = mysql_query($query);
      
    if (mysql_num_rows($result) == 0) {
      $query2 = "INSERT INTO Tag (text) VALUES('$tag')";
      $result = mysql_query($query2);
      $result = mysql_query($query);
    }
    $result_row = mysql_fetch_assoc($result);
    $tag_id = $result_row['id'];

    $query = "SELECT * FROM WebPageTag "
           . "WHERE webpagequery_id=$webpagequery_id "
           . "AND user_id=$user_id AND tag_id=$tag_id"; 
    $result = mysql_query($query);
    
    if (mysql_num_rows($result) == 0) {
      $query = "INSERT INTO WebPageTag (webpagequery_id, user_id, tag_id) "
             . "VALUES($webpagequery_id, $user_id, $tag_id)";
      $result = mysql_query($query);
    }
    $return_string .= "<returncode>1</returncode>";

    return $return_string;
  }
?>
